package com.campus.counseling.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campus.counseling.model.common.exception.ServiceException;
import com.campus.counseling.entity.SysArticle;
import com.campus.counseling.entity.SysUser;
import com.campus.counseling.model.mapper.SysArticleMapper;
import com.campus.counseling.model.dto.ArticleDTO;
import com.campus.counseling.model.query.ArticleQuery;
import com.campus.counseling.model.vo.ArticleVO;
import com.campus.counseling.service.ArticleService;
import com.campus.counseling.service.SysUserService;
import com.campus.counseling.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ArticleServiceImpl implements ArticleService {

    private final SysArticleMapper articleMapper;
    private final SysUserService userService;

    @Override
    public Page<ArticleVO> list(ArticleQuery query) {
        LambdaQueryWrapper<SysArticle> wrapper = new LambdaQueryWrapper<>();
        
        // 标题关键词
        wrapper.like(StringUtils.isNotBlank(query.getKeyword()), SysArticle::getTitle, query.getKeyword());
        
        // 文章类型
        wrapper.eq(StringUtils.isNotBlank(query.getCategory()), SysArticle::getCategory, query.getCategory());
        
        // 状态
        wrapper.eq(StringUtils.isNotBlank(query.getStatus()), SysArticle::getStatus, query.getStatus());
        
        // 角色可见性过滤
        String userRole = SecurityUtils.getCurrentUserRole();
        if ("superadmin".equals(userRole) || "admin".equals(userRole)) {
            // 管理员用户：如果指定了筛选条件，则按条件筛选
            if (StringUtils.isNotBlank(query.getVisibleRoles())) {
                wrapper.eq(SysArticle::getVisibleRoles, query.getVisibleRoles());
            }
        } else {
            // 非管理员用户：只能看到对自己可见的文章
            wrapper.and(w -> w
                .eq(SysArticle::getVisibleRoles, "all")
                .or()
                .eq(SysArticle::getVisibleRoles, userRole)
            );
        }
        
        // 排序
        wrapper.orderByAsc(SysArticle::getOrderNum)
               .orderByDesc(SysArticle::getCreateTime);
               
        // 查询原始数据
        Page<SysArticle> page = articleMapper.selectPage(query.toPage(), wrapper);
        
        // 创建结果页
        Page<ArticleVO> resultPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        // 转换记录
        resultPage.setRecords(page.getRecords().stream()
            .map(this::convertToVO)
            .collect(Collectors.toList()));
            
        return resultPage;
    }

    @Override
    public ArticleVO getArticle(Long id) {
        SysArticle article = articleMapper.selectById(id);
        if (article == null) {
            throw new ServiceException("文章不存在");
        }
        
        // 检查角色可见性
        String userRole = SecurityUtils.getCurrentUserRole();
        if (!"superadmin".equals(userRole) && !"admin".equals(userRole) 
            && !"all".equals(article.getVisibleRoles()) 
            && !article.getVisibleRoles().equals(userRole)) {
            throw new ServiceException("无权访问该文章");
        }
        
        return convertToVO(article);
    }

    @Override
    public void add(ArticleDTO articleDTO) {
        SysArticle article = new SysArticle();
        BeanUtils.copyProperties(articleDTO, article);
        
        // 设置作者ID
        article.setAuthorId(SecurityUtils.getCurrentUserId());
        // 设置初始排序号为当前最大值+1
        Integer maxOrderNum = articleMapper.selectMaxOrderNum();
        article.setOrderNum(maxOrderNum == null ? 1 : maxOrderNum + 1);
        // 设置其他初始值
        article.setViewCount(0);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        
        articleMapper.insert(article);
    }

    @Override
    public void update(Long id, ArticleDTO articleDTO) {
        SysArticle article = articleMapper.selectById(id);
        if (article == null) {
            throw new ServiceException("文章不存在");
        }
        
        BeanUtils.copyProperties(articleDTO, article);
        article.setUpdateTime(LocalDateTime.now());
        
        articleMapper.updateById(article);
    }

    @Override
    public void delete(Long id) {
        articleMapper.deleteById(id);
    }

    @Override
    public void updateOrder(Long id, Integer orderNum) {
        SysArticle article = articleMapper.selectById(id);
        if (article == null) {
            throw new ServiceException("文章不存在");
        }
        
        article.setOrderNum(orderNum);
        article.setUpdateTime(LocalDateTime.now());
        
        articleMapper.updateById(article);
    }

    private ArticleVO convertToVO(SysArticle article) {
        if (article == null) {
            return null;
        }
        
        ArticleVO vo = new ArticleVO();
        BeanUtils.copyProperties(article, vo);
        
        // 设置作者信息
        SysUser author = userService.getById(article.getAuthorId());
        if (author != null) {
            vo.setAuthorName(author.getRealName());
        }
        
        // 处理封面图片URL
        if (StringUtils.isNotBlank(article.getCoverUrl()) && !article.getCoverUrl().startsWith("/api")) {
            vo.setCoverUrl("/api" + article.getCoverUrl());
        }
        
        // 格式化时间
        if (article.getCreateTime() != null) {
            vo.setCreateTime(article.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        if (article.getUpdateTime() != null) {
            vo.setUpdateTime(article.getUpdateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        
        return vo;
    }
} 